<template>
  <view class="body">
    <nut-form :model-value="goodsConfig" ref="ruleForm">
      <view class="conCard">
        <view class="know" @click="toContrabandPage">了解禁运品</view>
        <view @click="chooseGoodsName">
          <nut-form-item prop="goodsName">
            <view class="tit">货物名称<span class="redIcon">*</span></view>
            <view class="flex-ld grayBg">
              <nut-input readonly :border="false" v-model="goodsConfig.goodsName" placeholder="请选择货物名称"></nut-input>
              <IconFont name="rect-right"></IconFont>
            </view>
          </nut-form-item>
        </view>
        <view @click="chooseGoodsType">
          <nut-form-item class="flex-ld" prop="goodsType">
            <view class="tit">货物类型<span class="redIcon">*</span></view>
            <view class="flex-ld grayBg">
              <nut-input readonly :border="false" v-model="goodsConfig.goodsType" placeholder="请选择货物类型"></nut-input>
              <IconFont name="rect-right"></IconFont>
            </view>
          </nut-form-item>
        </view>
        <view @click="chooseGoodsPack">
          <nut-form-item class="flex-ld" prop="goodsPack">
            <view class="tit">货物包装<span class="redIcon">*</span></view>
            <view class="flex-ld grayBg">
              <nut-input readonly :border="false" v-model="goodsConfig.goodsPack" placeholder="请选择货物包装"></nut-input>
              <IconFont name="rect-right"></IconFont>
            </view>
          </nut-form-item>
        </view>
      </view>
    </nut-form>

    <view class="countBox">
      <nut-cell title="货物重量">
        <template v-slot:link>
          <view>
            <nut-input-number min="0" step="0.01" decimal-places="2" v-model="goodsConfig.weight" />
          </view>
          <view>Kg</view>
        </template>
      </nut-cell>
      <nut-cell title="货物数量">
        <template v-slot:link>
          <view>
            <nut-input-number min="0" disabled v-model="goodsConfig.number" />
          </view>
          <view>件</view>
        </template>
      </nut-cell>
      <nut-cell title="货物体积">
        <template v-slot:link>
          <view>
            <nut-input-number disabled step="0.01" decimal-places="2" min="0" v-model="goodsConfig.volume" />
          </view>
          <view>m³</view>
        </template>
      </nut-cell>
      <view>
        <view v-for="(item, index) in specifications" :key="index" class="flex_item flex">
          <view class="count_bg">
            <nut-input placeholder="长" v-model="item.l" type="number"
              @input="item.l = item.l.replace(/^(0+)|[^\d]+/g, '')" input-align="center" />
            <span style="line-height: 50rpx;">cm</span>
          </view>
          <span>×</span>
          <view class="count_bg">
            <nut-input placeholder="宽" v-model="item.w" type="number"
              @input="item.w = item.w.replace(/^(0+)|[^\d]+/g, '')" input-align="center" />
            <span style="line-height: 50rpx;">cm</span>
          </view>
          <span>×</span>
          <view class="count_bg">
            <nut-input placeholder="高" v-model="item.h" type="number"
              @input="item.h = item.h.replace(/^(0+)|[^\d]+/g, '')" input-align="center" />
            <span style="line-height: 50rpx;">cm</span>
          </view>
          <span>×</span>
          <view class="count_bg">
            <nut-input placeholder="件数" v-model="item.sum" type="number"
              @input="item.sum = item.sum.replace(/^(0+)|[^\d]+/g, '')" input-align="center" />
            <span style="line-height: 50rpx;">件</span>
          </view>
          <view @click="add" v-if="index == 0">
            <image class="icon" src="@/assets/images/index/woyaofahuo_icon_tianjiaguige.png"></image>
          </view>
          <view @click="del(index)" v-else>
            <image class="icon" src="@/assets/images/index/woyaofahuo_icon_shanchuguige.png"></image>
          </view>
        </view>
      </view>
    </view>
  </view>
  <button class="btn" @click="confirm">确定</button>
</template>

<script setup lang='ts'>
import { ref, reactive, watch } from 'vue';
import Taro, { useDidShow, useReady, useRouter } from "@tarojs/taro";
import { IconFont } from '@nutui/icons-vue-taro';

const router = useRouter();


useReady(() => {
  Taro.setNavigationBarTitle({
    title: '货物信息'
  })
})

useDidShow(() => {
  console.log(router, 'router')
  // 1.货物信息存在的话就赋值
  if (router?.params.goods) {
    const goods = JSON.parse(router.params.goods);
    console.log(goods, '携带')
    goodsConfig.goodsName = goods.goodsName;
    goodsConfig.goodsType = goods.goodsType;
    goodsConfig.goodsPack = goods.packing;

    // 2.1按分号拆分货物规格数组
    const specificationsArray = goods.specifications.split(";");
    console.log(specificationsArray, '规格数组')
    if (specificationsArray.length !== 0 && specificationsArray[0] !== '') {
      // 按星号拆分每个元素，处理并赋值到新的数组对象
      const finalArray = specificationsArray.filter(element => element !== '').map(element => {
        const parts = element.split("*");
        return {
          w: parts[0].replace("cm", ""),
          h: parts[1].replace("cm", ""),
          l: parts[2].replace("cm", ""),
          sum: parts[3]
        };
      });
      console.log(finalArray, '重组后的规格数组对象');
      specifications.value = finalArray;
    }
    goodsConfig.weight = goods.weigh
    goodsConfig.volume = goods.goodsVolume
    goodsConfig.number = goods.goodsNumber
  } else {
    console.log('未携带')
  }
  // 2.赋值给货物名称货物类型货物包装
  let pages = Taro.getCurrentPages();
  let currPage = pages[pages.length - 1];
  console.log(currPage, 'currPAGE')
  if (currPage.__data__.goodsName) {
    goodsConfig.goodsName = currPage.__data__.goodsName
  }
  if (currPage.__data__.goodsType) {
    goodsConfig.goodsType = currPage.__data__.goodsType
  }
  if (currPage.__data__.goodsPack) {
    goodsConfig.goodsPack = currPage.__data__.goodsPack
  }
});

/* 货物规格的计算 start */
// 货物重量数量体积
const goodsConfig = reactive({
  goodsName: '', // 货物名称
  goodsType: '', // 货物类型
  goodsPack: '', // 货物包装
  weight: '', // 重量
  volume: '', // 体积
  number: '', // 数量
});

// 货物规格
const specifications = ref([{
  w: "",
  h: "",
  l: "",
  sum: "  ",
}])

// 监听规格触发计算
watch(() => specifications.value, (newVal) => {
  console.log(newVal, '监听')
  let all = 0;
  let sum = 0;
  specifications.value.forEach((item) => {
    all =
      all +
      Number(item.h != "" ? item.h : 0) *
      Number(item.l != "" ? item.l : 0) *
      Number(item.w != "" ? item.w : 0) *
      Number(item.sum != "" ? item.sum : 0);
    sum = sum + Number(item.sum != "" ? item.sum : 0);
  });
  console.log(all, 'all')
  if (all == 0) {
    goodsConfig.volume = "0";
    goodsConfig.number = "0";
  } else {
    all = Number((all / 1000000).toFixed(2))
    if (all == 0) {
      goodsConfig.volume = "0.01";
    } else {
      goodsConfig.volume = String(all);
    }
    goodsConfig.number = String(sum);
  }
}, { deep: true, immediate: true })

// 货物规格新增
function add() {
  specifications.value.push({
    w: "",
    h: "",
    l: "",
    sum: "  ",
  });
}

// 货物规格删除
function del(index: number) {
  specifications.value.splice(index, 1);
}
/* 货物规格的计算 end */


// 选择货物名称
function chooseGoodsName() {
  Taro.navigateTo({
    url: `/pages2/goodsPage/goodsName`
  });
}

// 选择货物类型
function chooseGoodsType() {
  Taro.navigateTo({
    url: `/pages2/goodsPage/goodsType`
  });
}

// 选择货物包装
function chooseGoodsPack() {
  Taro.navigateTo({
    url: `/pages2/goodsPage/goodsPack`
  });
}

// 了解禁运品
function toContrabandPage() {
  Taro.navigateTo({
    url: '/pages2/contrabandPage/index'
  });
}

// 点击确定 收集货物信息及规格重组数据并携带回显到确认订单页
function confirm() {
  console.log('收集货物规格goodsConfig', goodsConfig)
  console.log('收集货物规格数组', specifications.value)
  // 校验货物信息及重量
  if (!goodsConfig.goodsName) {
    Taro.showToast({
      title: '货物名称必选',
      icon: 'error',
      duration: 2000
    })
    return
  }

  if (!goodsConfig.goodsType) {
    Taro.showToast({
      title: '货物类型必选',
      icon: 'error',
      duration: 2000
    })
    return
  }

  if (!goodsConfig.goodsPack) {
    Taro.showToast({
      title: '货物包装必选',
      icon: 'error',
      duration: 2000
    })
    return
  }

  if (!goodsConfig.volume) {
    Taro.showToast({
      title: '货物重量未填',
      icon: 'error',
      duration: 2000
    })
    return
  }


  // 校验货物规格
  // 1.如果货物规格为空数组且每个值都为空就提示
  if (specifications.value.length > 0) {
    const allFieldsNotEmpty = specifications.value.every(item => (
      item.w && item.h && item.l && item.sum
    ));
    if (!allFieldsNotEmpty) {
      Taro.showToast({
        title: '货物规格未填',
        icon: 'error',
        duration: 2000
      })
    } else {
      // 2.重组货物规格变成字符串
      const resultString = specifications.value.map(obj => {
        const specificationString = `${obj.w}cm*${obj.h}cm*${obj.l}cm*${obj.sum}`;
        return specificationString;
      }).join(";");
      const specificationsString = resultString + ';';
      // console.log(specificationsString, '收集货物规格数组字符串');
      // 3.将货物规格跟货物信息组成一个对象
      const goods = {
        goodsName: goodsConfig.goodsName,
        goodsType: goodsConfig.goodsType,
        goodsVolume: goodsConfig.volume,
        packing: goodsConfig.goodsPack,
        weigh: goodsConfig.weight,
        goodsNumber: goodsConfig.number,
        upNumber: 0,
        specifications: specificationsString,
      }
      // return
      // 4.从货物信息页传递数据到确认订单页
      Taro.navigateTo({
        url: `/pages2/confirmPage/index?goods=${JSON.stringify(goods)}`
      });
    }
  } else {
    Taro.showToast({
      title: '货物规格未填',
      icon: 'error',
      duration: 2000
    })
  }
}

</script>


<style lang="scss">
.body {
  height: 100%;
  background: #f5f5f5;
  padding-bottom: 100rpx;
}


.nut-cell-group__wrap {
  background: #f5f5f5;
}

.nut-cell-group {
  width: 702rpx;
  margin: 0 auto;
}

.conCard {
  margin: 10rpx 0;
  position: relative;

  .know {
    position: absolute;
    right: 10rpx;
    top: 10rpx;
    font-size: 24rpx;
    color: #666666;
    z-index: 999;
  }

  .tit {
    font-size: 28rpx;
    color: #252525;
    margin-bottom: 8rpx;
    margin-right: 8rpx;

    .redIcon {
      display: inline-block;
      color: #FA5151;
    }
  }

  .grayBg {
    width: 654rpx;
    background: #f5f5f5;
    border-radius: 10rpx;
    margin: 0 auto;
    padding: 8rpx 12rpx;
    box-sizing: border-box;
  }

  .nut-input {
    background: #f5f5f5;
    padding: 8rpx 0 8rpx 0;
  }

}

.btn {
  margin: 0 auto;
  box-sizing: border-box;
  background: #0966FF;
  width: 700rpx;
  height: 88rpx;
  border-radius: 200rpx;
  opacity: 1;
  color: #fff;
  font-size: 32rpx;
  position: fixed;
  left: 50%;
  bottom: 10rpx;
  transform: translateX(-50%);
}

.flex {
  display: flex;
  justify-content: center;
  align-content: center;
}

.flex-ld {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
}


/* copy */
.countBox {
  width: 702rpx;
  margin: 10rpx auto;
  border-radius: 10rpx;
  background-color: #fff;
  padding-bottom: 20rpx;

  .flex_item {
    margin: 10rpx auto;
  }

  .nut-cell {
    margin: 0;
    box-shadow: none;
  }

  .icon {
    width: 30rpx;
    height: 30rpx;
  }

  .count_bg {
    background: #F5F5F5;
    font-size: 24rpx;
    display: flex;
    justify-content: center;
    align-content: center;
    margin: 0 5rpx;

    .nut-input {
      width: 100rpx;
      padding: 0;
      background: #F5F5F5;
      font-size: 24rpx;
    }
  }

}
</style>